﻿using System.Drawing;
using System.Drawing.Printing;
using System.Xml.Linq;
using DataManageSystem.Common;
using DataManageSystem.Data;
using DataManageSystem.Exceptions;
using DataManageSystem.Models;
using Microsoft.AspNetCore.Mvc.RazorPages;

namespace DataManageSystem.Services
{
    public class NoticeServices
    {
        private readonly ApplicationDbContext _context;

        public NoticeServices(ApplicationDbContext context)
        {
            _context = context;
        }
        public Result selectNoticeData(int pageNum, int pageSize, string title)
        {
            var query = _context.Notice.AsQueryable();
            if (!string.IsNullOrEmpty(title))
            {
                query = query.Where(u => u.Title.Contains(title));
            }

            int total = query.Count(); // 获取总记录数

            var notices = query
                .OrderByDescending(u => u.Id)
                .Skip((pageNum - 1) * pageSize)
                .Take(pageSize)
                .ToList();
            return Result.Success(notices, total);
        }

        public void add(Notice notice)
        {
            _context.Notice.Add(notice);
            _context.SaveChanges();
        }

        public void Delete(int id)
        {
            var notice = _context.Notice.FirstOrDefault(m => m.Id == id);
            if (notice != null)
            {
                _context.Notice.Remove(notice);
                _context.SaveChanges();
            }
            else
            {
                throw new ServiceException("数据不存在");
            }
        }
    }
}
